package com.zdp.security.userdetails;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdp.domain.User;
import com.zdp.mapper.UsersMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author sesshomaru
 * @date 2021/7/6
 * 密码升级
 */
@Transactional
@RequiredArgsConstructor
@Component
public class UserDetailsPasswordServiceImpl implements UserDetailsPasswordService {

    private final UsersMapper usersMapper;

    /**
     * @param userDetails 需要被升级密码的用户信息
     * @param newPassword 使用最新的加密方式加密后的新密码
     */
    @Override
    public UserDetails updatePassword(UserDetails userDetails, String newPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDetails.getUsername());
        User user = usersMapper.selectOne(queryWrapper);
        if (!Optional.ofNullable(user).isPresent()) {
            throw new UsernameNotFoundException("未找到用户名");
        }
        //更新密码
        User withUser = user.withPassword(newPassword);
        usersMapper.updateById(withUser);
        return withUser;
    }
}
